const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const soapService = require('./soapService');
const dbSync = require('./dbSync');
const scheduler = require('./scheduler');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 解析 SOAP 响应
function parseSoapResponse(soapResult) {
    try {
        console.log('SOAP响应原始数据:', JSON.stringify(soapResult));
        
        // 检查返回结果格式
        if (soapResult && soapResult.return && soapResult.return.$value) {
            // 尝试解析 SOAP 返回的 JSON 字符串
            try {
                const jsonStr = soapResult.return.$value;
                console.log('尝试解析JSON字符串:', jsonStr.substring(0, 200) + '...');
                const data = JSON.parse(jsonStr);
                return { success: true, data };
            } catch (jsonError) {
                console.error('JSON解析失败:', jsonError);
                // 返回原始字符串，如果无法解析为JSON
                return { 
                    success: true, 
                    data: soapResult.return.$value,
                    rawResponse: soapResult
                };
            }
        } else if (soapResult && soapResult.return) {
            // 直接返回 return 字段的值
            return { success: true, data: soapResult.return };
        } else {
            // 直接返回原始结果
            return { success: true, data: soapResult };
        }
    } catch (error) {
        console.error('解析 SOAP 响应失败:', error, '原始数据:', JSON.stringify(soapResult));
        return { success: false, error: '解析响应数据失败', rawResponse: soapResult };
    }
}

// 1. 现金银行明细查询接口
app.get('/api/cash-bank-detail', async (req, res) => {
    try {
        const { startDate, endDate } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getCashBankDetail(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('现金银行明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// POST 方法
app.post('/api/cash-bank-detail', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getCashBankDetail(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('现金银行明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 2. 仓库金额明细查询接口
app.get('/api/store-amount-detail', async (req, res) => {
    try {
        const { startDate, endDate } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getStoreAmountDetail(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('仓库金额明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/store-amount-detail', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getStoreAmountDetail(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('仓库金额明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 3. 仓库金额查询接口
app.get('/api/store-amount', async (req, res) => {
    try {
        const { startDate } = req.query;
        console.log('startDate', startDate);
        if (!startDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getStoreAmount(startDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('仓库金额查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/store-amount', async (req, res) => {
    try {
        const { startDate } = req.body;
        
        if (!startDate) {
            return res.status(400).json({ success: false, error: '开始日期是必填项' });
        }
        
        const result = await soapService.getStoreAmount(startDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('仓库金额查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 4. 收入金额查询接口
app.get('/api/income-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getIncomeAmount(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('收入金额查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/income-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getIncomeAmount(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('收入金额查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 5. 费用金额查询接口
app.get('/api/fee-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getFeeAmount(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('费用金额查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/fee-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getFeeAmount(startDate, endDate);
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('费用金额查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 6. 公司盈利查询接口
app.get('/api/company-profit', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getCompanyProfit(
            startDate, 
            endDate, 
            company, 
            sales, 
            trader, 
            minNo, 
            no
        );
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('公司盈利查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/company-profit', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getCompanyProfit(
            startDate, 
            endDate, 
            company, 
            sales, 
            trader, 
            minNo, 
            no
        );
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('公司盈利查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 7. 盈利明细查询接口
app.get('/api/profit-detail', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getProfitDetail(
            startDate, 
            endDate, 
            company, 
            sales, 
            trader, 
            minNo, 
            no
        );
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('盈利明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/profit-detail', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getProfitDetail(
            startDate, 
            endDate, 
            company, 
            sales, 
            trader, 
            minNo, 
            no
        );
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('盈利明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 8. 销售明细查询接口
app.get('/api/sell-detail', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.query;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getSellDetail(
            startDate, 
            endDate, 
            company, 
            sales, 
            trader, 
            minNo, 
            no
        );
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('销售明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sell-detail', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await soapService.getSellDetail(
            startDate, 
            endDate, 
            company, 
            sales, 
            trader, 
            minNo, 
            no
        );
        const parsedResult = parseSoapResponse(result);
        
        if (parsedResult.success) {
            res.json({ success: true, data: parsedResult.data });
        } else {
            res.status(500).json({ success: false, error: parsedResult.error });
        }
    } catch (error) {
        console.error('销售明细查询失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 数据同步接口
app.post('/api/sync/cash-bank-detail', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncCashBankDetail(startDate, endDate);
        res.json(result);
    } catch (error) {
        console.error('同步现金银行明细失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/store-amount-detail', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncStoreAmountDetail(startDate, endDate);
        res.json(result);
    } catch (error) {
        console.error('同步仓库金额明细失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/store-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncStoreAmount(startDate, endDate);
        res.json(result);
    } catch (error) {
        console.error('同步仓库金额失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/income-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncIncomeAmount(startDate, endDate);
        res.json(result);
    } catch (error) {
        console.error('同步收入金额失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/fee-amount', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncFeeAmount(startDate, endDate);
        res.json(result);
    } catch (error) {
        console.error('同步费用金额失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/company-profit', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncCompanyProfit(startDate, endDate, company, sales, trader, minNo, no);
        res.json(result);
    } catch (error) {
        console.error('同步公司盈利失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/profit-detail', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncProfitDetail(startDate, endDate, company, sales, trader, minNo, no);
        res.json(result);
    } catch (error) {
        console.error('同步盈利明细失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/sell-detail', async (req, res) => {
    try {
        const { startDate, endDate, company, sales, trader, minNo, no } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncSellDetail(startDate, endDate, company, sales, trader, minNo, no);

        res.send(result);
    } catch (error) {
        console.error('同步销售明细失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.post('/api/sync/all', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        const result = await dbSync.syncAllData(startDate, endDate);
        res.json(result);
    } catch (error) {
        console.error('同步所有数据失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

app.get('/api/sync/status', async (req, res) => {
    try {
        const result = await dbSync.getSyncStatus();
        res.json(result);
    } catch (error) {
        console.error('获取同步状态失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 手动触发定时任务接口
app.post('/api/scheduler/sync-now', async (req, res) => {
    try {
        // 异步执行同步任务，不阻塞响应
        scheduler.syncNow().catch(err => console.error('手动同步失败:', err));
        res.json({ success: true, message: '已触发同步前一天数据任务，请查看日志了解详情' });
    } catch (error) {
        console.error('触发同步任务失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 手动同步指定日期数据
app.post('/api/scheduler/sync-date', async (req, res) => {
    try {
        const { date } = req.body;
        
        if (!date) {
            return res.status(400).json({ success: false, error: '日期参数是必填项' });
        }
        
        // 验证日期格式
        if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
            return res.status(400).json({ success: false, error: '日期格式不正确，请使用 YYYY-MM-DD 格式' });
        }
        
        // 异步执行同步任务，不阻塞响应
        scheduler.syncDate(date).catch(err => console.error(`同步指定日期 ${date} 失败:`, err));
        res.json({ success: true, message: `已触发同步指定日期 ${date} 的数据任务，请查看日志了解详情` });
    } catch (error) {
        console.error('触发同步任务失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 手动同步指定日期范围数据
app.post('/api/scheduler/sync-date-range', async (req, res) => {
    try {
        const { startDate, endDate } = req.body;
        
        if (!startDate || !endDate) {
            return res.status(400).json({ success: false, error: '开始日期和结束日期是必填项' });
        }
        
        // 验证日期格式
        if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate)) {
            return res.status(400).json({ success: false, error: '日期格式不正确，请使用 YYYY-MM-DD 格式' });
        }
        
        // 异步执行同步任务，不阻塞响应
        scheduler.syncDateRange(startDate, endDate).catch(err => 
            console.error(`同步日期范围 ${startDate} 至 ${endDate} 失败:`, err)
        );
        res.json({ 
            success: true, 
            message: `已触发同步日期范围 ${startDate} 至 ${endDate} 的数据任务，请查看日志了解详情` 
        });
    } catch (error) {
        console.error('触发同步任务失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 手动同步当前月份数据
app.post('/api/scheduler/sync-current-month', async (req, res) => {
    try {
        // 异步执行同步任务，不阻塞响应
        scheduler.syncCurrentMonth().catch(err => console.error('同步当前月份数据失败:', err));
        res.json({ success: true, message: '已触发同步当前月份数据任务，请查看日志了解详情' });
    } catch (error) {
        console.error('触发同步任务失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 手动同步上个月数据
app.post('/api/scheduler/sync-last-month', async (req, res) => {
    try {
        // 异步执行同步任务，不阻塞响应
        scheduler.syncLastMonth().catch(err => console.error('同步上个月数据失败:', err));
        res.json({ success: true, message: '已触发同步上个月数据任务，请查看日志了解详情' });
    } catch (error) {
        console.error('触发同步任务失败:', error);
        res.status(500).json({ success: false, error: '服务器内部错误' });
    }
});

// 根路径
app.get('/', (req, res) => {
    res.send('数据服务 API 运行正常');
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
    
    // 启动定时任务
    const job = scheduler.startScheduler();
    console.log('定时任务已启动，每天凌晨1点将同步前一天数据');
}); 